import { login, getUserInfo, getUserDetailById } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
import { resetRouter, constantRoutes } from '@/router'
const state = {
  token: getToken(),
  userInfo: {},
  menus: []
}
const mutations = {
  setToken(state, layload) {
    state.token = layload
    setToken(layload)
  },
  setUserInfo(state, layload) {
    state.userInfo = layload
  },
  setmenus(state, layload) {
    state.menus = [...constantRoutes, ...layload]
  }
}

const actions = {
  async login(context, data) {
    const res = await login(data)
    context.commit('setToken', res)
  },
  async getUserInfo(context) {
    const userInfo = await getUserInfo()
    const userDetail = await getUserDetailById(userInfo.userId)
    context.commit('setUserInfo', { ...userInfo, ...userDetail })
    return userInfo
  },
  removeToken() {
    state.token = ''
  },
  removeuserInfo() {
    state.userInfo = {}
  },
  logout(state) {
    state.userInfo = {}
    removeToken()
    resetRouter()
  }

}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
